package com.jinyu.jyly.ui.mall.detail;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseActivity;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.MallDetailInfo;
import com.jinyu.jyly.ui.mine.buy.MineBuyActivity;
import com.jinyu.jyly.utils.AES;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;

/**
 * 商城详情
 */
public class MallDetailActivity extends BaseActivity<MallDetailPresenter> implements MallDetailContract.View ,View.OnClickListener{

    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_title_view)
    RelativeLayout rlTitleView;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_kucun_num)
    TextView tvKucunNum;
    @BindView(R.id.tv_guige)
    TextView tvGuige;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.btn_buy)
    Button btnBuy;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.tv_jianding_price)
    TextView tvJiandingPrice;
    @BindView(R.id.banner)
    Banner mBanner;

    private MallDetailPresenter presenter;
    private int mId;

    @Override
    public int getLayout() {
        return R.layout.activity_mall_detail;
    }

    @Override
    protected MallDetailPresenter getPresenter() {
        if (presenter == null) {
            presenter = new MallDetailPresenter(this, this);
        }
        return presenter;
    }

    @Override
    protected void initEventAndData() {
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        btnBuy.setOnClickListener(this);
        ivBack.setOnClickListener(this);

        Intent intent = getIntent();
        mId = intent.getIntExtra("id", -1);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", mId);
            String pamam = AES.encryptToHexString(jsonObject.toString());
            mTipDialog.show();
            presenter.getMallDetail(pamam);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailer(Throwable throwable) {
        mTipDialog.dismiss();
    }

    /**
     * 获取商品详情
     * @param infoBean
     */
    @Override
    public void onMallDetail(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                try {
                    String result = AES.decrypt(data);
                    Gson gson = new Gson();
                    MallDetailInfo mallDetailInfo = gson.fromJson(result, MallDetailInfo.class);
                    if (mallDetailInfo != null) {
                        tvTitle.setText(mallDetailInfo.getName());
                        tvPrice.setText("当前价\n￥" + mallDetailInfo.getPrice() + "");
                        tvKucunNum.setText("库号：" + mallDetailInfo.getStock_num());
                        tvGuige.setText("规格：" + mallDetailInfo.getSpecial());
                        tvOldPrice.setText("原始价:\n￥"+mallDetailInfo.getRough_price());
                        tvJiandingPrice.setText("鉴定价:\n￥"+mallDetailInfo.getOld_price());

                        List<String> thumblist = mallDetailInfo.getThumb();
                        setBanner(thumblist);

                        int enable = mallDetailInfo.getEnable();
//                        if(enable == 0){
//                            //开馆
//                            btnBuy.setOnClickListener(this);
//                            btnBuy.setBackground(getResources().getDrawable(R.mipmap.icon_buy_nowse));
//                            btnBuy.setText("立即购买");
//                        }else{
//                            //未开馆
//                            btnBuy.setOnClickListener(null);
//                            btnBuy.setBackground(getResources().getDrawable(R.color.gray05));
//                            btnBuy.setText("还未开始，请等待");
//                        }

                        String content = mallDetailInfo.getContent();
                        String linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/html.css\" type=\"text/css\"/>";
                        String body = "<html><header>" + linkCss + "</header>" + content
                                + "</body></html>";
                        webview.loadDataWithBaseURL(null, body, "text/html", "utf-8", null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 提交订单
     * @param infoBean
     */
    @Override
    public void addOrder(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()){
            case 200:
                String data = infoBean.getData();
                Intent mBuyIntent = new Intent(this, MineBuyActivity.class);
                startActivity(mBuyIntent);
                showToast("提交成功");
                finish();
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:break;
        }
    }

    /**
     * 设置banner
     * @param mList
     */
    private void setBanner(List<String> mList) {
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //CIRCLE_INDICATOR
        //设置图片加载器，图片加载器在下方
        mBanner.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        mBanner.setImages(mList);
        //设置轮播图的标题集合
        mBanner.setBannerTitles(mList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        mBanner.setBannerAnimation(Transformer.Accordion);//Default  //Accordion
        //设置轮播间隔时间
        mBanner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        mBanner.isAutoPlay(false);
        //设置指示器的位置，小点点，左中右。
        mBanner.setIndicatorGravity(BannerConfig.CENTER) //CENTER
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
//                          .setOnBannerListener(this)
                //必须最后调用的方法，启动轮播图。
                .start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_buy:
                //提交订单
                setSignOutApp();
                break;
            default:break;
        }
    }



    //立即购买
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private void setSignOutApp() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("立即购买")
                .setMessage("您确定购买该商品吗？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        try {

                            boolean showing = mTipDialog.isShowing();
                            if(!showing){
                                mTipDialog.show();
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id", mId); //37
                                String param = AES.encryptToHexString(jsonObject.toString());
                                presenter.addOrder(param);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }


    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            RequestOptions options = new RequestOptions();
            options.error(R.mipmap.space_list);
            Glide.with(context).load(path)
                    .apply(options)
                    .into(imageView);
        }
    }
}
